"""
为统计某个年份范围的数据对数据库做拆分 将json数据分给字段
"""
import json
import sys

import facade
from xjlibrary.our_file_dir import BaseDir


class DealSql(object):

    def __init__(self):
        self.curPath = BaseDir.get_file_dir_absolute(__file__)
        self.configfile = BaseDir.get_new_path(self.curPath, "db.ini")
        self.logger = facade.get_streamlogger()
        self.mysqlutils = facade.MysqlUtiles(self.configfile, "db", logger=self.logger, cursorsnum=1)

    def dealissue(self):
        sql = "select * from issue where failcount=1 limit 1000"
        rows = self.mysqlutils.SelectFromDB(sql)
        if rows:
            for row in rows:
                sql = "insert ignore into issue_copy1 (issue_url,vol,issue,issuedate,jid,stat,issuenum) values ('%s','%s','%s','%s','%s',1,%d)"
                jsondicts = json.loads(row["jsonmsg"])
                issue = jsondicts["issue"]
                date = jsondicts["date"]
                jid = jsondicts["jid"]
                vol = jsondicts["vol"]
                issue_url = row["issue_url"]
                issuenum = int(row["issuenum"])
                sql = sql % (issue_url, vol, issue, date, jid, issuenum)
                self.mysqlutils.ExeSqlToDB(sql)
                sql = "update issue set failcount=0 where issue_url='{}'".format(issue_url)
                self.mysqlutils.ExeSqlToDB(sql)
                return True
        else:
            return "break"

    def dealarticle(self):
        sql = "select * from article where failcount=1 limit 1000"
        rows = self.mysqlutils.SelectFromDB(sql)
        if rows:
            for row in rows:
                sql = "insert ignore into article_copy1 (doi,vol,issue,issuedate,jid,num,issuurl,stat,failcount) values ('%s','%s','%s','%s','%s','%s','%s',1,0)"
                jsondicts = json.loads(row["jsonmsg"])
                issue = jsondicts["issue"]
                date = jsondicts["date"]
                jid = jsondicts["jid"]
                vol = jsondicts["vol"]
                issue_url = row["issuurl"]
                doi = row["doi"]
                num = row["num"]
                sql = sql % (doi, vol, issue, date, jid, num, issue_url)
                self.mysqlutils.ExeSqlToDB(sql)
                sql = "update article set failcount=0 where doi='{}'".format(doi)
                self.mysqlutils.ExeSqlToDB(sql)
                return True
        else:
            return "break"


if __name__ == "__main__":
    deal = DealSql()
    while True:
        result = deal.dealarticle()
        if result == "break":
            break
